package org.servlet;

import org.apache.log4j.Logger;
import org.domain.Account;
import org.domain.Order;
import org.service.CartService;
import org.service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class ConfirmOrderServlet extends HttpServlet {
    private final static String VIEW_ORDER = "/WEB-INF/JSP/order/ViewOrder.jsp";
    private static final String CONFIRM_ORDER = "/WEB-INF/order/ConfirmOrder.jsp";
    private static Logger logger = Logger.getLogger(Class.class);
    private OrderService orderService;
    private CartService cartService;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        orderService = new OrderService();
        cartService = new CartService();
        HttpSession session = request.getSession();
        Order order = (Order) session.getAttribute("order");
        if (order.isShippingAddressRequired()) {
            String shipToFirstName = request.getParameter("shipToFirstName");
            String shipToLastName = request.getParameter("shipToLastName");
            String shipAddress1 = request.getParameter("shipAddress1");
            String shipAddress2 = request.getParameter("shipAddress2");
            String shipCity = request.getParameter("shipCity");
            String shipState = request.getParameter("shipState");
            String shipZip = request.getParameter("shipZip");
            String shipCountry = request.getParameter("shipCountry");
            order.setShipToFirstName(shipToFirstName);
            order.setShipToLastName(shipToLastName);
            order.setShipAddress1(shipAddress1);
            order.setShipAddress2(shipAddress2);
            order.setShipCity(shipCity);
            order.setShipState(shipState);
            order.setShipZip(shipZip);
            order.setShipCountry(shipCountry);
            request.setAttribute("order", order);
            order.setShippingAddressRequired(false);
            request.getRequestDispatcher(CONFIRM_ORDER).forward(request, response);
        } else {
            orderService.insertOrder(order);
            Account account = (Account) session.getAttribute("account");
            logger.info(String.format("User (%s) Confirm a New Form.", account.getUsername()));
            logger.info(String.format("User (%s) Clear His Cart.", account.getUsername()));
            cartService.removeCartByUserId(account.getUsername());
            session.setAttribute("cart", null);
            request.getRequestDispatcher("newOrderFinished").forward(request, response);
        }

    }
}
